package com.burst.reptile.modular.monitor.service.impl;

import com.burst.reptile.common.constant.Constants;
import com.burst.reptile.common.constant.ScheduleConstants;
import com.burst.reptile.common.exception.job.TaskException;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.common.utils.job.CronUtils;
import com.burst.reptile.common.utils.job.ScheduleUtils;
import com.burst.reptile.modular.monitor.entity.SysJob;
import com.burst.reptile.modular.monitor.mapper.SysJobMapper;
import com.burst.reptile.modular.monitor.service.ISysJobService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.List;

import javax.annotation.PostConstruct;

import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 定时任务调度表 服务实现类
 * </p>
 *
 * @author wujin
 * @since 2020-06-09
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements ISysJobService {

	private final Scheduler scheduler;

	/**
	 * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
	 */
	@PostConstruct
	public void init() throws SchedulerException, TaskException {
		log.info("------定时任务开始初始化------");
		scheduler.clear();
		List<SysJob> jobList = this.list();
		for (SysJob job : jobList) {
			// 如果是过去时则删除
			String cronExpression = job.getCronExpression();
			LocalDateTime nextExecution = CronUtils.getNextExecution(cronExpression);
			if(ToolUtil.isEmpty(nextExecution)) {
				this.removeById(job.getJobId());
			}else {
				ScheduleUtils.createScheduleJob(scheduler, job);
			}
		}
		log.info("------定时任务开始初始化完成------");
	}
	
	@Override
	public Page<SysJob> selectPageJobList(Page<SysJob> page, SysJob job) {
		return this.baseMapper.selectPageJobList(page, job);
	}

	@Override
	public List<SysJob> selectJobList(SysJob job) {
		return this.baseMapper.selectJobList(job);
	}

	@Override
	public SysJob selectJobById(Long jobId) {
		return this.baseMapper.selectJobById(jobId);
	}

	@Override
	@Transactional
	public int pauseJob(SysJob job) throws SchedulerException {
		Long jobId = job.getJobId();
		String jobGroup = job.getJobGroup();
		job.setJobStatus(ScheduleConstants.Status.PAUSE.getValue());
		int rows = this.baseMapper.updateJob(job);
		if (rows > 0) {
			scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
		}
		return rows;
	}

	@Override
	@Transactional
	public int resumeJob(SysJob job) throws SchedulerException {
		Long jobId = job.getJobId();
		String jobGroup = job.getJobGroup();
		job.setJobStatus(ScheduleConstants.Status.NORMAL.getValue());
		int rows = this.baseMapper.updateJob(job);
		if (rows > 0) {
			scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
		}
		return rows;
	}

	@Override
	@Transactional
	public int deleteJob(SysJob job) throws SchedulerException {
		Long jobId = job.getJobId();
		String jobGroup = job.getJobGroup();
		int rows = this.baseMapper.deleteJobById(jobId);
		if (rows > 0) {
			if(ScheduleUtils.checkExists(scheduler, job.getJobId(), Constants.PUBLISH)) {
				scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
			}
		}
		return rows;
	}

	@Override
	@Transactional
	public void deleteJobByIds(Long[] jobIds) throws SchedulerException {
		for (Long jobId : jobIds) {
			SysJob job = this.baseMapper.selectJobById(jobId);
			deleteJob(job);
		}

	}

	@Override
	@Transactional
	public int changeStatus(SysJob job) throws SchedulerException {
		int rows = 0;
		String status = job.getJobStatus();
		if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
			rows = resumeJob(job);
		} else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
			rows = pauseJob(job);
		}
		return rows;
	}

	@Override
	@Transactional
	public void run(SysJob job) throws SchedulerException {
		Long jobId = job.getJobId();
		String jobGroup = job.getJobGroup();
		SysJob properties = selectJobById(job.getJobId());
		// 参数
		JobDataMap dataMap = new JobDataMap();
		dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
		scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap);
	}

	@Override
	@Transactional
	public int insertJob(SysJob job) throws SchedulerException, TaskException {
		int rows = this.baseMapper.insertJob(job);
		if (rows > 0) {
			ScheduleUtils.createScheduleJob(scheduler, job);
		}
		return rows;
	}

	@Override
	@Transactional
	public int updateJob(SysJob job) throws SchedulerException, TaskException {
		SysJob properties = selectJobById(job.getJobId());
		int rows = this.baseMapper.updateJob(job);
		if (rows > 0) {
			updateSchedulerJob(job, properties.getJobGroup());
		}
		return rows;
	}

	/**
	 * 更新任务
	 * 
	 * @param job      任务对象
	 * @param jobGroup 任务组名
	 */
	public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
		Long jobId = job.getJobId();
		// 判断是否存在
		JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
		if (scheduler.checkExists(jobKey)) {
			// 防止创建时存在数据问题 先移除，然后在执行创建操作
			scheduler.deleteJob(jobKey);
		}
		ScheduleUtils.createScheduleJob(scheduler, job);
	}

	@Override
	public boolean checkCronExpressionIsValid(String cronExpression) {
		return CronUtils.isValid(cronExpression);
	}

}
